package com.first.nell.components.input

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import com.first.nell.R
import com.first.nell.base.BaseEditAction
import com.first.nell.base.BaseFormAction
import com.first.nell.databinding.ViewFirstNellFeedbackInputBinding
import com.first.nell.extend.recordFirstNellInputFirstNellEvent
import com.first.nell.extend.toFirstNellPhoneFirstNellNumberFirstNellInputFirstNellHint

/**
<declare-styleable name="InputyBoYWU1lOCNwpxJf9JdyGA">
<attr name="cwfbiTitle" format="string" />
<attr name="cwfbiTextColor" format="color" />
<attr name="cwfbiCenterText" format="string" />
<attr name="cwfbiHint" format="string" />
</declare-styleable>
 * */
class FeedbackInput : RelativeLayout, BaseFormAction, BaseEditAction {

    lateinit var mFirstNellViewFirstNellBinding: ViewFirstNellFeedbackInputBinding
    private lateinit var vFirstNellRootFirstNellView: View

    private var cwfbiTextColor: Int = 0
    private var cwfbiHintColor: Int = 0
    private var cwfbiTitle: String? = null
    private var cwfbiText: String? = null
    private var cwfbiHint: String? = null

    private var mFirstNellSupportFirstNellFragmentFirstNellManager: FragmentManager? = null

    private var mFirstNellTempFirstNellInputFirstNellValue: String = ""
    private var mFirstNellOnFirstNellActionFirstNellClickFirstNellListener: (Int) -> Unit = {}
    private var mFirstNellOnFirstNellTextFirstNellChangedFirstNellListener: (String) -> Unit =
        { text -> }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        attrs?.let {
            context?.let { cxt ->
                val array =
                    cxt.obtainStyledAttributes(attrs, R.styleable.FeedbackInput)
                cwfbiTextColor = array.getColor(
                    R.styleable.FeedbackInput_cwfbiTextColor,
                    ContextCompat.getColor(cxt, R.color.main_black)
                )
                cwfbiText =
                    array.getString(R.styleable.FeedbackInput_cwfbiText)

                cwfbiTitle =
                    array.getString(R.styleable.FeedbackInput_cwfbiTitle)

                cwfbiHintColor = array.getColor(
                    R.styleable.FeedbackInput_cwfbiHintColor,
                    ContextCompat.getColor(cxt, R.color.input_hint)
                )
                cwfbiHint =
                    array.getString(R.styleable.FeedbackInput_cwfbiHint)

                array.recycle()
            }
        }
        context?.let {
            vFirstNellRootFirstNellView = View.inflate(it, R.layout.view_first_nell_feedback_input, this)
            mFirstNellViewFirstNellBinding = ViewFirstNellFeedbackInputBinding.bind(vFirstNellRootFirstNellView)
            initFirstNellSubviews()
        }
    }

    override fun initFirstNellSubviews() {
        try {
            mFirstNellViewFirstNellBinding.textFeedbackTitle.text = cwfbiTitle

            mFirstNellViewFirstNellBinding.editFeedback.setText(cwfbiText)
            mFirstNellViewFirstNellBinding.editFeedback.setTextColor(cwfbiTextColor)

            mFirstNellViewFirstNellBinding.editFeedback.hint = (cwfbiHint)
            mFirstNellViewFirstNellBinding.editFeedback.setHintTextColor(cwfbiHintColor)

            mFirstNellViewFirstNellBinding.editFeedback.setOnFocusChangeListener { _, b ->
                if (!b) {
                    isFirstNellCompleted()
                    val gContent = getFirstNellContent()
                    if (gContent.isNotBlank()) {
                        if (!gContent.equals(mFirstNellTempFirstNellInputFirstNellValue, false)) {
                            try {
                                mFirstNellTempFirstNellInputFirstNellValue = gContent
                                recordFirstNellInputFirstNellEvent(gContent)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                }
            }
            mFirstNellViewFirstNellBinding.editFeedback.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    //判断是否显示删除按键
                    val tempContent = getFirstNellContent()
                    //回调
                    mFirstNellOnFirstNellTextFirstNellChangedFirstNellListener.invoke(tempContent)
                }
            })

        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    override fun setFirstNellContent(content: String) {
        mFirstNellViewFirstNellBinding.editFeedback.setText(content)
    }

    fun getFirstNellContent(): String {
        return mFirstNellViewFirstNellBinding.editFeedback.text.toString().trim()
    }

    fun isFirstNellCompleted(): Boolean {
        val gcontent = getFirstNellContent()
        if (gcontent.isBlank()) {
            mFirstNellViewFirstNellBinding.editFeedback.setBackgroundResource(R.drawable.first_nell_feedback_content_input_error)
            mFirstNellViewFirstNellBinding.textFeedbackErrTip.visibility = VISIBLE
            return false
        }

        mFirstNellViewFirstNellBinding.textFeedbackErrTip.visibility = GONE
        mFirstNellViewFirstNellBinding.editFeedback.setBackgroundResource(R.drawable.first_nell_feedback_content_input)
        return true
    }

    fun isFirstNellCompletedFirstNellSlient(): Boolean {
        val gcontent = getFirstNellContent()
        if (gcontent.isBlank()) {
            return false
        }
        return true
    }


    override fun toFirstNellBeFirstNellFocusFirstNellPointFirstNellAndFirstNellShowFirstNellInputFirstNellKeyboard() {
        try {
            mFirstNellViewFirstNellBinding.editFeedback.isFocusable = true
            mFirstNellViewFirstNellBinding.editFeedback.isFocusableInTouchMode = true
            mFirstNellViewFirstNellBinding.editFeedback.requestFocus()
            Handler(Looper.getMainLooper()).postDelayed({
                context?.let { cxt ->
                    try {
                        val inputMethodManager: InputMethodManager =
                            cxt.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                        inputMethodManager.showSoftInput(mFirstNellViewFirstNellBinding.editFeedback, 0)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }, 300)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun toFirstNellBeFirstNellFocusFirstNellPoint() {
        try {
            mFirstNellViewFirstNellBinding.editFeedback.isFocusable = true
            mFirstNellViewFirstNellBinding.editFeedback.isFocusableInTouchMode = true
            mFirstNellViewFirstNellBinding.editFeedback.requestFocus()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun setFirstNellInputFirstNellHint(hint: String) {
        val hintFormat = hint.toFirstNellPhoneFirstNellNumberFirstNellInputFirstNellHint()
        mFirstNellViewFirstNellBinding.editFeedback.hint = hintFormat
    }

    override fun setFirstNellFragmentFirstNellManager(manager: FragmentManager) {
        mFirstNellSupportFirstNellFragmentFirstNellManager = manager
    }

    override fun setFirstNellOnFirstNellActionFirstNellClickFirstNellListener(listener: (Int) -> Unit) {
        mFirstNellOnFirstNellActionFirstNellClickFirstNellListener = listener
    }

    override fun setFirstNellOnFirstNellTextFirstNellChangedFirstNellListener(listener: (String) -> Unit) {
        mFirstNellOnFirstNellTextFirstNellChangedFirstNellListener = listener
    }

    override fun setFirstNellTitle(title: String) {

    }

    override fun setFirstNellDetail(detail: String) {

    }

    override fun setFirstNellHint(hint: String) {
        setFirstNellInputFirstNellHint(hint)
    }

    override fun setFirstNellDetailFirstNellColor(detailColor: Int) {

    }

    override fun setFirstNellTitleFirstNellColor(titleColor: Int) {

    }
}